package com.software.backend.login.repository;

import com.software.backend.login.utils.SessionContextUtils;
import okhttp3.*;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 王俊坤
 * @version 1.0
 * @date 2022/12/25 12:54
 */
@Repository
public class AuthCodeRepositoryImpl implements AuthCodeResository{

    private boolean hasSuccess = false;

    OkHttpClient okHttpClient = new OkHttpClient();

    private SessionContextUtils sessionContextUtils = SessionContextUtils.getInstance();

    @Override
    public String createAuthCode() {
        return String.valueOf((int)(Math.random()*1000000 + 1000000)).substring(1);
    }

    @Override
    public void saveAuthCode(String authCode, HttpSession session, String phoneNumber) {
        session.removeAttribute("authCode");
        session.setAttribute("authCode",authCode);
        sessionContextUtils.addSession(session, phoneNumber);
    }

    @Override
    public void sendMessageToPhone(String authCode, String phoneNumber) {
        System.out.printf("55555");
        FormBody formBody = new FormBody.Builder()
                .add("account", "C00241913")
                .add("password", "267e052e9e73605bee01d57cc9105d01")
                .add("mobile", phoneNumber)
                .add("content", "您的验证码是：" + authCode + "。请不要把验证码泄露给其他人。")
                .build();
        Request request = new Request.Builder().url("https://106.ihuyi.com/webservice/sms.php?method=Submit").post(formBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                System.out.printf("发送短信", "访问失败");
                hasSuccess = false;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                System.out.printf("收到的回执", result);
            }
        });
    }

    @Override
    public boolean hasCodeTimeOut(String phoneNumber) {
        return sessionContextUtils.canReAddSession(phoneNumber);
    }

    @Override
    public boolean varifyAuthCode(String authCode, String phoneNumber, HttpSession session) {
        String gotCode = sessionContextUtils.getSession(phoneNumber);
        if (gotCode.equals(authCode)){
            sessionContextUtils.delSession(phoneNumber);
            sessionContextUtils.delSession(session);
            return true;
        }else {
            return false;
        }
    }
}
